package wormDemo2;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Random;

public class WormPanel {
	private int rows = 10;
	private int cols = 50;
	
	private HashSet<Node> foods = new HashSet<Node>();
	
	private Worm worm;
	public WormPanel(){
		this.worm = new Worm();
		this.initFoods(6);
	}
	
	public Worm getWorm() {
		return worm;
	}

	public void setWorm(Worm worm) {
		this.worm = worm;
	}
/*
 * 在控制台加入“0”
 * （1）“0”放入一个集合（HashSet）当中
 * （2）第一不能放在蛇身上
 * （3）不能在边框上，而且不能出边框
 * （4）随机
 * （5）
 * 
 * */
	//初始化foods方法
	public void initFoods(int n){
		Random random = new Random();
		while(true){
			
			int i = random.nextInt(rows-2)+1;  //保证不落在0坐标
			int j = random.nextInt(cols-2)+1;
			if(worm.contains(new Node(i,j))){
				continue;
			}
			Node node = new Node(i,j);
			if(foods.contains(node)){
				continue;
			}
			foods.add(node);
			if(foods.size()==n){
				break;
			}
		}
	}
	
	public void print(){
		for(int i=0;i<rows;i++){
			for(int j=0;j<cols;j++){
				if(i==0 || i==rows-1){
					System.out.print("-");
				}
				else if(j==0 || j==cols-1){
					System.out.print("|");
				}
				else if(this.worm.contains(new Node(i,j))){
					System.out.print("#");
				}
				else if(this.foods.contains(new Node(i,j))){
					System.out.print("0");
				}
				else {
					System.out.print(" ");
				}
			}
			System.out.println();
		}
	}
	public class Worm {
		private LinkedList<Node> nodes = new LinkedList<Node>();
		private int dir;
		//分为四个固定的方向
		public final static int UP = -10;
		public static final int DOWN = 10;
		public static final int LEFT = -1;
		public static final int RIGHT = 1;
		
		//按照文档图来写的初始化
		public Worm(){
			nodes.add(new Node(3,9));
			nodes.add(new Node(4,9));
			nodes.add(new Node(5,9));
			nodes.add(new Node(5,10));
			nodes.add(new Node(5,11));
			nodes.add(new Node(6,11));
			nodes.add(new Node(7,11));
			this.dir=UP;
		}
		//传递linkedlist<node>()
		public Worm(LinkedList<Node> nodes){
			this.nodes.clear();
			//把传递过来的nodes给this.nodes
			this.nodes.addAll(nodes);
		}
		
		public void step(){
			// 取得原来的坐标head
			Node head = this.nodes.getFirst();
			int i = head.getI()+dir/10;
			int j = head.getJ()+dir%10;
			//创建移动后的头的坐标
			Node head1 = new Node(i,j);
			//加头
			this.nodes.addFirst(head1);
			if(foods.contains(head1)){
				foods.remove(head1);
				return;
			}
			//去尾
			this.nodes.removeLast();
			System.out.println(this.nodes.toString());
		}
		
		public void step(int dir){
			//换方向
			//相反方向的移动，用RuntimeException:运行期异常,程序正在运行，突然出现错误，突然终止程序
			if(this.dir+dir==0){
				throw new RuntimeException("方向错误");
			}
			this.dir=dir;
			step();
		}
		
		public boolean contains(Node node){
			return this.nodes.contains(node);
		}
		
	}
}
